import router from '@/router'
import { useUserStore } from '@/stores/userStore.ts'
import { message } from 'ant-design-vue'

let firstFetchLoginUser = true

/**
 * 全局权限校验
 */
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  let currentLoginUser = userStore.loginUser

  if (firstFetchLoginUser) {
    await userStore.fetchLoginUserInfo()
    currentLoginUser = userStore.loginUser
    firstFetchLoginUser = false
  }

  const toUrl = to.path

  // 定义权限规则
  if (toUrl.startsWith('/admin')) {
    if (!currentLoginUser || currentLoginUser.userRole !== 'admin') {
      message.error('未授权')
      next(`/user/login?redirect=${to.fullPath}`)
      return
    }
  }
  next()
})
